﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// 缓存池
/// </summary>
public class CacheUtility
{
    static HttpContext context;

    static CacheUtility cache;

    static int WEATHER_CACHE_DB_HOUR = 3;
    static float WEATHER_CACHE_PAGE_HOUR = 0.5f;
    static int CITY_CACHE_HOUR = 12;

    private CacheUtility()
    {
    }


    public static bool isHotCity(String cityCode)
    {
        string key = "all_hot_list";
        List<string> list =null;
        if (context.Cache[key] != null)
        {
            list = (List<string>)context.Cache[key];
        }
        else
        {
            List<County> mlist= DataBaseUtility.getAllHotCounty();
            list=new List<string>();
            foreach (County item in mlist)
            {
                list.Add(item.CityCode);
            }
            context.Cache.Add(key, list, null, DateTime.Now.AddHours(CITY_CACHE_HOUR), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
        }
        return list.Contains(cityCode);
    }

    public static CacheUtility GetInstance(HttpContext _context)
    {
        if (cache == null)
        {
            cache = new CacheUtility();
            context = _context;
        }
        return cache;
    }

    private void AsyncCallback(byte[] bytes)
    {

    }

    /// <summary>
    /// 得到所有的省信息
    /// </summary>
    /// <returns></returns>
    public String GetProvice()
    {
        string key = "all_provice";
        if (context.Cache[key] != null)
        {
            return context.Cache[key].ToString();
        }
        else
        {
            string Result = FormatUtility.FormatList(DataBaseUtility.loadProvince(), FormatUtility.PROVINCE);
            context.Cache.Add(key, Result, null, DateTime.Now.AddHours(CITY_CACHE_HOUR), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            return Result;
        }

    }

    /// <summary>
    /// 得到所有的城市信息
    /// </summary>
    /// <returns></returns>
    public String GetCity(string code)
    {
        string key = "city_" + code;
        if (context.Cache[key] != null)
        {
            return context.Cache[key].ToString();
        }
        else
        {
            string Result = FormatUtility.FormatList(DataBaseUtility.LoadCity(code), FormatUtility.CITY);
            context.Cache.Add(key, Result, null, DateTime.Now.AddHours(CITY_CACHE_HOUR), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            return Result;
        }

    }

    /// <summary>
    /// 得到所有的县区信息
    /// </summary>
    /// <returns></returns>
    public String GetCounty(string code)
    {
        string key = "county_" + code;
        if (context.Cache[key] != null)
        {
            return context.Cache[key].ToString();
        }
        else
        {
            string Result = FormatUtility.FormatList(DataBaseUtility.LoadCounty(code), FormatUtility.COUNTY);
            context.Cache.Add(key, Result, null, DateTime.Now.AddHours(CITY_CACHE_HOUR), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            return Result;
        }
    }

    /// <summary>
    /// 得到所有的县区信息
    /// </summary>
    /// <returns></returns>
    public String GetHotCity()
    {
        string key = "hot_city";
        if (context.Cache[key] != null)
        {
            return context.Cache[key].ToString();
        }
        else
        {
            string Result = FormatUtility.FormatList(DataBaseUtility.getAllHotCounty(), FormatUtility.COUNTY);
            context.Cache.Add(key, Result, null, DateTime.Now.AddHours(CITY_CACHE_HOUR), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            return Result;
        }
    }

    public bool ClearCache()
    {
        IDictionaryEnumerator eme = context.Cache.GetEnumerator();
        while (eme.MoveNext())
        {
            if (eme.Key.ToString().StartsWith("c_"))
            {
                context.Cache.Remove(eme.Key.ToString());
            }
        }
        return true;
    }

    public String GetWeather(string code, int type)
    {
        try
        {
            string r_code = String.Format("c_{0}_{1}", code, type);
            if (context.Cache[r_code] != null)
            {
                String result = context.Cache[r_code].ToString();
                if (!result.StartsWith("{"))
                {
                    context.Cache.Remove(r_code);
                    return GetWeather(code, type);
                }
                return result;
            }
            else
            {
                String wInfo = DataBaseUtility.ReadWeather(code, type);
                String result = "";
                bool isTimeout = false;
                if (wInfo.Length > 0)
                {
                    string[] array = wInfo.Split('|');
                    result = array[1];
                    DateTime dt = DateTime.Parse(array[0]);
                    //判断是否超时
                    if (dt.AddHours(WEATHER_CACHE_DB_HOUR) < DateTime.Now)
                    {
                        isTimeout = true;
                    }

                    if (context.Cache[r_code] == null) //从数据库中读入缓存
                    {
                        context.Cache.Add(r_code, result, null, DateTime.Now.AddHours(WEATHER_CACHE_PAGE_HOUR), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                    }
                }

                if (wInfo.Length == 0 || isTimeout)
                {                   
                    result = HttpUtility.HttpRequest(FormatUtility.GetWeatherUrl(code, type));
                   
                    if (result.StartsWith("{"))
                    {
                        if (type == FormatUtility.SIMPLE)
                        {
                            string result_2 = HttpUtility.HttpRequest(FormatUtility.GetWeatherUrl(code, FormatUtility.SIMPLE_2));
                            result = FormatUtility.UnitSimpleWeather(result, result_2);
                        }

                        if (context.Cache[r_code] != null) { context.Cache.Remove(r_code); }
                        context.Cache.Add(r_code, result, null, DateTime.Now.AddHours(WEATHER_CACHE_PAGE_HOUR), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
                        DataBaseUtility.SaveWeather(result, code, type);
                    }
                    else
                    {
                        result = wInfo;
                    }
                }
                return result;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public string  CheckCity(string wcode)
    {
        string result = HttpUtility.HttpRequest(FormatUtility.GetWeatherUrl(wcode, FormatUtility.DETAILS));
        string r_code = String.Format("c_{0}_{1}", wcode, FormatUtility.DETAILS);
        if (result.StartsWith("{"))
        {
            if (context.Cache[r_code] != null) { context.Cache.Remove(r_code); }
            context.Cache.Add(r_code, result, null, DateTime.Now.AddHours(WEATHER_CACHE_PAGE_HOUR), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Normal, null);
            DataBaseUtility.SaveWeather(result, wcode, FormatUtility.DETAILS);
            //DataBaseUtility.UpdateHotCity(wcode, true);
            return wcode+"|true";
        }
        else
        {
            //DataBaseUtility.UpdateHotCity(wcode, false);
            return wcode+"|true";
        }
    }
}


